package com.lytxmd.boxtest.http;

import android.content.Context;

import com.google.gson.Gson;
import com.lytxmd.boxtest.bean.ResultBean;
import com.lytxmd.boxtest.utils.LoadingDialog;
import com.lytxmd.boxtest.utils.LogUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zhangyinglong on 2017/5/16.
 */
public abstract class CallbackTemplate<T> extends Callback<ResultBean<T>> {
    private Context mContext;
    public CallbackTemplate(Context context){
        mContext = context;
    }

    @Override
    public void onBefore(Request request, int id) {
        super.onBefore(request, id);
        LoadingDialog.showDialogForLoading(mContext);
    }

    @Override
    public void onAfter(int id) {
        super.onAfter(id);
        LoadingDialog.cancelDialogForLoading();
    }

    public ResultBean<T> parseNetworkResponse(Response response, int id) throws Exception {
        //获取我们的数据
        String result = response.body().string();
        LogUtils.json(result);
        JSONObject jsonObject = new JSONObject(result);
        int status = jsonObject.getInt("status");
        String detail = jsonObject.getString("detail");
        String data = jsonObject.get("data").toString();

        Gson gson = new Gson();
        //获取传入类型 通过反射获取的
        Type genericSuperclass = getClass().getGenericSuperclass();//获取带有泛型的父类
        Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();  //获取泛型参数的数组，可能有多个
        Class<T> clazz = (Class<T>) actualTypeArguments[0];
        // 将数据转换成 对象
        T o = gson.fromJson(data, clazz);
        ResultBean<T> resultBean = new ResultBean<>();
        resultBean.setData(o);
        resultBean.setDetail(detail);
        resultBean.setStatus(status);
        return resultBean;
    }


    @Override
    public void onError(Call call, Exception e, int id) {
        error(e.getMessage());
    }


    @Override
    public void onResponse(ResultBean<T> response, int id) {
        int code = response.getStatus();
        LogUtils.i("----------code="+code);
        if(code==0){
            LogUtils.i("----------"+response.getData().getClass());
            success(response.getData());
        }else{
            error(response.getDetail());
        }
    }


    public abstract void success(T t);

    public abstract void error(String msg);

}